// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 统一处理表单提交事件
    initFormSubmissions();
    
    // 统一处理搜索功能
    initSearchFunctions();
    
    // 统一处理按钮点击事件
    initButtonClickHandlers();
    
    // 初始化页面功能
    initPage();
});

// 初始化表单提交事件
function initFormSubmissions() {
    // 定义表单配置
    const formConfigs = [
        { id: 'loginForm', handler: validateLoginForm },
        { id: 'registerForm', handler: validateRegisterForm },
        { id: 'profileForm', handler: updateProfile },
        { id: 'passwordForm', handler: changePassword },
        { id: 'addBookForm', handler: addBook },
        { id: 'editBookForm', handler: updateBook },
        { id: 'addCategoryForm', handler: addCategory },
        { id: 'editCategoryForm', handler: updateCategory }
    ];
    
    // 批量绑定表单提交事件
    formConfigs.forEach(config => {
        const form = document.getElementById(config.id);
        if (form) {
            form.addEventListener('submit', function(e) {
                e.preventDefault();
                config.handler();
            });
        }
    });
}

// 初始化搜索功能
function initSearchFunctions() {
    // 定义搜索配置
    const searchConfigs = [
        { btnId: 'searchBtn', inputId: 'searchInput', handler: searchBooks },
        { btnId: 'categorySearchBtn', inputId: 'categorySearchInput', handler: searchCategoryBooks },
        { btnId: 'borrowSearchBtn', inputId: 'borrowSearchInput', handler: searchBorrowRecords }
    ];
    
    // 批量绑定搜索按钮点击事件
    searchConfigs.forEach(config => {
        const btn = document.getElementById(config.btnId);
        if (btn) {
            btn.addEventListener('click', config.handler);
        }
    });
    
    // 批量绑定回车键搜索
    searchConfigs.forEach(config => {
        const input = document.getElementById(config.inputId);
        if (input) {
            input.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    config.handler();
                }
            });
        }
    });
}

// 初始化按钮点击事件
function initButtonClickHandlers() {
    // 返回分类列表按钮
    const backToCategoriesBtn = document.getElementById('backToCategoriesBtn');
    if (backToCategoriesBtn) {
        backToCategoriesBtn.addEventListener('click', function() {
            document.getElementById('categoriesContainer').style.display = 'grid';
            document.getElementById('categoryBooksSection').style.display = 'none';
            document.getElementById('categoryTitle').textContent = '分类下的图书';
        });
    }
    
    // 退出登录功能
    const logoutLink = document.getElementById('logoutLink');
    if (logoutLink) {
        logoutLink.addEventListener('click', function(e) {
            e.preventDefault();
            logout();
        });
    }
    
    // 为所有导航链接添加点击事件
    const navLinks = document.querySelectorAll('.nav-link');
    navLinks.forEach(link => {
        link.addEventListener('click', function() {
            // 可以在这里添加页面切换的动画效果
            console.log('切换到页面:', this.getAttribute('href'));
        });
    });
}

// 检查用户是否为管理员
function checkAdminPermission() {
    return new Promise((resolve) => {
        const currentUser = JSON.parse(localStorage.getItem('currentUser'));
        if (!currentUser) {
            resolve(false);
            return;
        }
        
        // 发送请求到后端检查用户权限
        fetch('/api/users/current/admin')
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                resolve(data.data);
            } else {
                resolve(false);
            }
        })
        .catch(error => {
            console.error('检查管理员权限失败:', error);
            resolve(false);
        });
    });
}

// 登录表单验证函数
function validateLoginForm() {
    // 获取表单元素
    const username = document.getElementById('username');
    const password = document.getElementById('password');
    const usernameError = document.getElementById('usernameError');
    const passwordError = document.getElementById('passwordError');
    
    // 重置错误信息
    usernameError.textContent = '';
    passwordError.textContent = '';
    username.classList.remove('error');
    password.classList.remove('error');
    
    let isValid = true;
    
    // 验证用户名
    if (!username.value.trim()) {
        usernameError.textContent = '请输入用户名';
        username.classList.add('error');
        isValid = false;
    }
    
    // 验证密码
    if (!password.value.trim()) {
        passwordError.textContent = '请输入密码';
        password.classList.add('error');
        isValid = false;
    }
    
    // 如果验证通过，发送登录请求
    if (isValid) {
        loginUser(username.value.trim(), password.value.trim());
    }
}

// 用户登录函数
function loginUser(username, password) {
    // 显示加载状态
    const loginButton = document.querySelector('#loginForm .btn');
    const originalText = loginButton.textContent;
    loginButton.textContent = '登录中...';
    loginButton.disabled = true;
    
    // 发送登录请求
    fetch('/api/users/login', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            username: username,
            password: password
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            // 登录成功，保存用户信息到本地存储
            localStorage.setItem('currentUser', JSON.stringify(data.data));
            alert('登录成功！');
            
            // 根据用户角色跳转到不同的页面
            if (data.data.role === 'ADMIN') {
                // 管理员跳转到管理员中心
                window.location.href = 'admin.html';
            } else {
                // 普通用户跳转到图书列表页面
                window.location.href = 'books.html';
            }
        } else {
            alert('登录失败：' + (data.message || '用户名或密码错误'));
        }
    })
    .catch(error => {
        console.error('登录请求失败:', error);
        alert('登录请求失败，请稍后重试');
    })
    .finally(() => {
        // 恢复按钮状态
        loginButton.textContent = originalText;
        loginButton.disabled = false;
    });
}

// 注册表单验证函数
function validateRegisterForm() {
    // 获取表单元素
    const username = document.getElementById('username');
    const realName = document.getElementById('realName');
    const phone = document.getElementById('phone');
    const password = document.getElementById('password');
    const confirmPassword = document.getElementById('confirmPassword');
    
    const usernameError = document.getElementById('usernameError');
    const realNameError = document.getElementById('realNameError');
    const phoneError = document.getElementById('phoneError');
    const passwordError = document.getElementById('passwordError');
    const confirmPasswordError = document.getElementById('confirmPasswordError');
    
    // 重置错误信息
    usernameError.textContent = '';
    realNameError.textContent = '';
    phoneError.textContent = '';
    passwordError.textContent = '';
    confirmPasswordError.textContent = '';
    
    [username, realName, phone, password, confirmPassword].forEach(el => {
        el.classList.remove('error');
    });
    
    let isValid = true;
    
    // 验证用户名
    if (!username.value.trim()) {
        usernameError.textContent = '请输入用户名';
        username.classList.add('error');
        isValid = false;
    }
    
    // 验证真实姓名
    if (!realName.value.trim()) {
        realNameError.textContent = '请输入真实姓名';
        realName.classList.add('error');
        isValid = false;
    }
    
    // 验证手机号
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phone.value.trim()) {
        phoneError.textContent = '请输入手机号';
        phone.classList.add('error');
        isValid = false;
    } else if (!phoneRegex.test(phone.value.trim())) {
        phoneError.textContent = '手机号格式不正确';
        phone.classList.add('error');
        isValid = false;
    }
    
    // 验证密码
    if (!password.value.trim()) {
        passwordError.textContent = '请输入密码';
        password.classList.add('error');
        isValid = false;
    } else if (password.value.trim().length < 6) {
        passwordError.textContent = '密码长度不能少于6位';
        password.classList.add('error');
        isValid = false;
    }
    
    // 验证确认密码
    if (!confirmPassword.value.trim()) {
        confirmPasswordError.textContent = '请再次输入密码';
        confirmPassword.classList.add('error');
        isValid = false;
    } else if (password.value.trim() !== confirmPassword.value.trim()) {
        confirmPasswordError.textContent = '两次输入的密码不一致';
        confirmPassword.classList.add('error');
        isValid = false;
    }
    
    // 如果验证通过，发送注册请求
    if (isValid) {
        registerUser({
            username: username.value.trim(),
            realName: realName.value.trim(),
            phone: phone.value.trim(),
            password: password.value.trim()
        });
    }
}

// 用户注册函数
function registerUser(userData) {
    // 显示加载状态
    const registerButton = document.querySelector('#registerForm .btn');
    const originalText = registerButton.textContent;
    registerButton.textContent = '注册中...';
    registerButton.disabled = true;
    
    // 发送注册请求
    fetch('/api/users', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(userData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            alert('注册成功！');
            // 跳转到登录页面
            window.location.href = 'login.html';
        } else {
            alert('注册失败：' + (data.message || '请稍后重试'));
        }
    })
    .catch(error => {
        console.error('注册请求失败:', error);
        alert('注册请求失败，请稍后重试');
    })
    .finally(() => {
        // 恢复按钮状态
        registerButton.textContent = originalText;
        registerButton.disabled = false;
    });
}

// 加载用户个人信息
function loadUserProfile() {
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    if (!currentUser) {
        alert('请先登录');
        window.location.href = 'login.html';
        return;
    }
    
    // 填充表单数据
    document.getElementById('username').value = currentUser.username;
    document.getElementById('realName').value = currentUser.realName || '';
    document.getElementById('phone').value = currentUser.phone || '';
    
    // 获取完整的用户信息
    fetch(`/api/users/${currentUser.id}`)
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            document.getElementById('realName').value = data.data.realName || '';
            document.getElementById('phone').value = data.data.phone || '';
        }
    })
    .catch(error => {
        console.error('加载用户信息失败:', error);
    });
}

// 更新用户个人信息
function updateProfile() {
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    if (!currentUser) {
        alert('请先登录');
        window.location.href = 'login.html';
        return;
    }
    
    const realName = document.getElementById('realName').value.trim();
    const phone = document.getElementById('phone').value.trim();
    
    // 表单验证
    const realNameError = document.getElementById('realNameError');
    const phoneError = document.getElementById('phoneError');
    
    // 重置错误信息
    realNameError.textContent = '';
    phoneError.textContent = '';
    document.getElementById('realName').classList.remove('error');
    document.getElementById('phone').classList.remove('error');
    
    let isValid = true;
    
    // 验证真实姓名
    if (!realName) {
        realNameError.textContent = '请输入真实姓名';
        document.getElementById('realName').classList.add('error');
        isValid = false;
    }
    
    // 验证手机号
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phone) {
        phoneError.textContent = '请输入手机号';
        document.getElementById('phone').classList.add('error');
        isValid = false;
    } else if (!phoneRegex.test(phone)) {
        phoneError.textContent = '手机号格式不正确';
        document.getElementById('phone').classList.add('error');
        isValid = false;
    }
    
    // 如果验证通过，发送更新请求
    if (isValid) {
        // 显示加载状态
        const saveButton = document.querySelector('#profileForm .btn');
        const originalText = saveButton.textContent;
        saveButton.textContent = '保存中...';
        saveButton.disabled = true;
        
        fetch(`/api/users/${currentUser.id}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                realName: realName,
                phone: phone
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                alert('个人信息更新成功！');
                // 更新本地存储的用户信息
                currentUser.realName = realName;
                currentUser.phone = phone;
                localStorage.setItem('currentUser', JSON.stringify(currentUser));
            } else {
                alert('更新失败：' + (data.message || '请稍后重试'));
            }
        })
        .catch(error => {
            console.error('更新请求失败:', error);
            alert('更新请求失败，请稍后重试');
        })
        .finally(() => {
            // 恢复按钮状态
            saveButton.textContent = originalText;
            saveButton.disabled = false;
        });
    }
}

// 修改密码
function changePassword() {
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    if (!currentUser) {
        alert('请先登录');
        window.location.href = 'login.html';
        return;
    }
    
    const newPassword = document.getElementById('newPassword').value.trim();
    const confirmPassword = document.getElementById('confirmPassword').value.trim();
    
    // 表单验证
    const newPasswordError = document.getElementById('newPasswordError');
    const confirmPasswordError = document.getElementById('confirmPasswordError');
    
    // 重置错误信息
    newPasswordError.textContent = '';
    confirmPasswordError.textContent = '';
    
    [document.getElementById('newPassword'), document.getElementById('confirmPassword')].forEach(el => {
        el.classList.remove('error');
    });
    
    let isValid = true;
    
    // 验证新密码
    if (!newPassword) {
        newPasswordError.textContent = '请输入新密码';
        document.getElementById('newPassword').classList.add('error');
        isValid = false;
    } else if (newPassword.length < 6) {
        newPasswordError.textContent = '新密码长度不能少于6位';
        document.getElementById('newPassword').classList.add('error');
        isValid = false;
    }
    
    // 验证确认密码
    if (!confirmPassword) {
        confirmPasswordError.textContent = '请再次输入新密码';
        document.getElementById('confirmPassword').classList.add('error');
        isValid = false;
    } else if (newPassword !== confirmPassword) {
        confirmPasswordError.textContent = '两次输入的密码不一致';
        document.getElementById('confirmPassword').classList.add('error');
        isValid = false;
    }
    
    // 如果验证通过，发送修改密码请求
    if (isValid) {
        // 显示加载状态
        const changePasswordButton = document.querySelector('#passwordForm .btn');
        const originalText = changePasswordButton.textContent;
        changePasswordButton.textContent = '修改中...';
        changePasswordButton.disabled = true;
        
        fetch(`/api/users/${currentUser.id}/password`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                newPassword: newPassword
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                alert('密码修改成功！');
                // 清空表单
                document.getElementById('newPassword').value = '';
                document.getElementById('confirmPassword').value = '';
            } else {
                alert('修改失败：' + (data.message || '请稍后重试'));
            }
        })
        .catch(error => {
            console.error('修改密码请求失败:', error);
            alert('修改密码请求失败，请稍后重试');
        })
        .finally(() => {
            // 恢复按钮状态
            changePasswordButton.textContent = originalText;
            changePasswordButton.disabled = false;
        });
    }
}

// 加载图书列表
function loadBooks(page = 1, size = 12) {
    const booksContainer = document.getElementById('booksContainer');
    const paginationContainer = document.getElementById('pagination');
    
    // 显示加载状态
    booksContainer.innerHTML = '<p style="text-align: center; grid-column: 1 / -1;">加载中...</p>';
    
    // 发送请求获取图书列表
    fetch(`/api/books?page=${page}&size=${size}`)
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            displayBooks(data.data.records);
            displayPagination(data.data, page);
        } else {
            booksContainer.innerHTML = '<p style="text-align: center; grid-column: 1 / -1;">加载图书列表失败</p>';
        }
    })
    .catch(error => {
        console.error('加载图书列表失败:', error);
        booksContainer.innerHTML = '<p style="text-align: center; grid-column: 1 / -1;">加载图书列表失败，请稍后重试</p>';
    });
}

// 显示图书列表
function displayBooks(books) {
    const booksContainer = document.getElementById('booksContainer');
    
    if (!books || books.length === 0) {
        booksContainer.innerHTML = '<p style="text-align: center; grid-column: 1 / -1;">暂无图书数据</p>';
        return;
    }
    
    booksContainer.innerHTML = books.map(book => `
        <div class="book-card">
            <div class="book-cover">
                <span>📚</span>
            </div>
            <div class="book-info">
                <h3>${book.title}</h3>
                <p>作者: ${book.author}</p>
                <p>分类: ${book.categoryId || '未分类'}</p>
                <p>库存: ${book.stock}</p>
                <div class="book-actions">
                    <button class="btn btn-primary" onclick="borrowBook(${book.id})">借阅</button>
                </div>
            </div>
        </div>
    `).join('');
}

// 显示分页控件
function displayPagination(pageData, currentPage) {
    const paginationContainer = document.getElementById('pagination');
    const totalPages = pageData.pages;
    
    if (totalPages <= 1) {
        paginationContainer.innerHTML = '';
        return;
    }
    
    let paginationHTML = '';
    
    // 上一页按钮
    if (currentPage > 1) {
        paginationHTML += `<button class="btn btn-secondary" onclick="loadBooks(${currentPage - 1})">上一页</button>`;
    }
    
    // 页码按钮
    for (let i = Math.max(1, currentPage - 2); i <= Math.min(totalPages, currentPage + 2); i++) {
        if (i === currentPage) {
            paginationHTML += `<button class="btn btn-primary" disabled>${i}</button>`;
        } else {
            paginationHTML += `<button class="btn btn-secondary" onclick="loadBooks(${i})">${i}</button>`;
        }
    }
    
    // 下一页按钮
    if (currentPage < totalPages) {
        paginationHTML += `<button class="btn btn-secondary" onclick="loadBooks(${currentPage + 1})">下一页</button>`;
    }
    
    paginationContainer.innerHTML = paginationHTML;
}

// 搜索图书
function searchBooks() {
    const keyword = document.getElementById('searchInput').value.trim();
    const booksContainer = document.getElementById('booksContainer');
    
    if (!keyword) {
        loadBooks(1);
        return;
    }
    
    // 显示加载状态
    booksContainer.innerHTML = '<p style="text-align: center; grid-column: 1 / -1;">搜索中...</p>';
    
    // 发送搜索请求
    fetch(`/api/books/search?keyword=${encodeURIComponent(keyword)}&page=1&size=12`)
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            displayBooks(data.data.records);
            displayPagination(data.data, 1);
        } else {
            booksContainer.innerHTML = '<p style="text-align: center; grid-column: 1 / -1;">搜索失败</p>';
        }
    })
    .catch(error => {
        console.error('搜索图书失败:', error);
        booksContainer.innerHTML = '<p style="text-align: center; grid-column: 1 / -1;">搜索失败，请稍后重试</p>';
    });
}

// 借阅图书
function borrowBook(bookId) {
    // 检查用户是否已登录
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    if (!currentUser) {
        alert('请先登录后再进行借阅操作');
        window.location.href = 'login.html';
        return;
    }
    
    // 确认借阅
    if (!confirm('确定要借阅这本书吗？')) {
        return;
    }
    
    // 发送借阅请求
    fetch('/api/borrows', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            userId: currentUser.id,
            bookId: bookId
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            alert('借阅成功！');
            // 重新加载图书列表
            loadBooks();
        } else {
            alert('借阅失败：' + (data.message || '请稍后重试'));
        }
    })
    .catch(error => {
        console.error('借阅请求失败:', error);
        alert('借阅请求失败，请稍后重试');
    });
}

// 加载图书分类
function loadCategories() {
    const categoriesContainer = document.getElementById('categoriesContainer');
    
    // 显示加载状态
    categoriesContainer.innerHTML = '<p style="text-align: center; grid-column: 1 / -1;">加载中...</p>';
    
    // 发送请求获取分类列表
    fetch('/api/categories')
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            displayCategories(data.data);
        } else {
            categoriesContainer.innerHTML = '<p style="text-align: center; grid-column: 1 / -1;">加载分类列表失败</p>';
        }
    })
    .catch(error => {
        console.error('加载分类列表失败:', error);
        categoriesContainer.innerHTML = '<p style="text-align: center; grid-column: 1 / -1;">加载分类列表失败，请稍后重试</p>';
    });
}

// 显示图书分类
function displayCategories(categories) {
    const categoriesContainer = document.getElementById('categoriesContainer');
    
    if (!categories || categories.length === 0) {
        categoriesContainer.innerHTML = '<p style="text-align: center; grid-column: 1 / -1;">暂无分类数据</p>';
        return;
    }
    
    categoriesContainer.innerHTML = categories.map(category => `
        <div class="category-card" onclick="loadCategoryBooks(${category.id}, '${category.name}')">
            <div class="category-header">
                <span>📚</span>
            </div>
            <div class="category-info">
                <h3>${category.name}</h3>
                <p>${category.description || '暂无描述'}</p>
            </div>
        </div>
    `).join('');
}

// 加载分类下的图书
function loadCategoryBooks(categoryId, categoryName) {
    // 隐藏分类列表，显示图书列表
    document.getElementById('categoriesContainer').style.display = 'none';
    document.getElementById('categoryBooksSection').style.display = 'block';
    document.getElementById('categoryTitle').textContent = `${categoryName} 分类下的图书`;
    
    // 加载该分类下的图书
    loadCategoryBooksByPage(categoryId, 1);
}

// 按页加载分类下的图书
function loadCategoryBooksByPage(categoryId, page = 1, size = 12) {
    const booksContainer = document.getElementById('categoryBooksContainer');
    const paginationContainer = document.getElementById('categoryBooksPagination');
    
    // 显示加载状态
    booksContainer.innerHTML = '<p style="text-align: center; grid-column: 1 / -1;">加载中...</p>';
    
    // 发送请求获取分类下的图书列表
    fetch(`/api/books/category/${categoryId}?page=${page}&size=${size}`)
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            displayCategoryBooks(data.data.records);
            displayCategoryBooksPagination(data.data, page, categoryId);
        } else {
            booksContainer.innerHTML = '<p style="text-align: center; grid-column: 1 / -1;">加载图书列表失败</p>';
        }
    })
    .catch(error => {
        console.error('加载分类下图书列表失败:', error);
        booksContainer.innerHTML = '<p style="text-align: center; grid-column: 1 / -1;">加载图书列表失败，请稍后重试</p>';
    });
}

// 显示分类下的图书
function displayCategoryBooks(books) {
    const booksContainer = document.getElementById('categoryBooksContainer');
    
    if (!books || books.length === 0) {
        booksContainer.innerHTML = '<p style="text-align: center; grid-column: 1 / -1;">该分类下暂无图书</p>';
        return;
    }
    
    booksContainer.innerHTML = books.map(book => `
        <div class="book-card">
            <div class="book-cover">
                <span>📚</span>
            </div>
            <div class="book-info">
                <h3>${book.title}</h3>
                <p>作者: ${book.author}</p>
                <p>库存: ${book.stock}</p>
                <div class="book-actions">
                    <button class="btn btn-primary" onclick="borrowBook(${book.id})">借阅</button>
                </div>
            </div>
        </div>
    `).join('');
}

// 显示分类下图书的分页控件
function displayCategoryBooksPagination(pageData, currentPage, categoryId) {
    const paginationContainer = document.getElementById('categoryBooksPagination');
    const totalPages = pageData.pages;
    
    if (totalPages <= 1) {
        paginationContainer.innerHTML = '';
        return;
    }
    
    let paginationHTML = '';
    
    // 上一页按钮
    if (currentPage > 1) {
        paginationHTML += `<button class="btn btn-secondary" onclick="loadCategoryBooksByPage(${categoryId}, ${currentPage - 1})">上一页</button>`;
    }
    
    // 页码按钮
    for (let i = Math.max(1, currentPage - 2); i <= Math.min(totalPages, currentPage + 2); i++) {
        if (i === currentPage) {
            paginationHTML += `<button class="btn btn-primary" disabled>${i}</button>`;
        } else {
            paginationHTML += `<button class="btn btn-secondary" onclick="loadCategoryBooksByPage(${categoryId}, ${i})">${i}</button>`;
        }
    }
    
    // 下一页按钮
    if (currentPage < totalPages) {
        paginationHTML += `<button class="btn btn-secondary" onclick="loadCategoryBooksByPage(${categoryId}, ${currentPage + 1})">下一页</button>`;
    }
    
    paginationContainer.innerHTML = paginationHTML;
}

// 搜索分类下的图书
function searchCategoryBooks() {
    const keyword = document.getElementById('categorySearchInput').value.trim();
    // 这里可以实现更复杂的搜索功能
    // 目前简化处理，可以添加按关键词搜索分类下图书的功能
    alert('搜索功能待完善');
}

// 加载借阅记录
function loadBorrowRecords(page = 1, size = 10) {
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    if (!currentUser) {
        alert('请先登录');
        window.location.href = 'login.html';
        return;
    }
    
    const recordsContainer = document.getElementById('borrowRecordsContainer');
    const paginationContainer = document.getElementById('borrowPagination');
    
    // 显示加载状态
    recordsContainer.innerHTML = '<p>加载中...</p>';
    
    // 发送请求获取借阅记录
    fetch(`/api/borrows/user/${currentUser.id}?page=${page}&size=${size}`)
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            displayBorrowRecords(data.data.records);
            displayBorrowPagination(data.data, page);
        } else {
            recordsContainer.innerHTML = '<p>加载借阅记录失败</p>';
        }
    })
    .catch(error => {
        console.error('加载借阅记录失败:', error);
        recordsContainer.innerHTML = '<p>加载借阅记录失败，请稍后重试</p>';
    });
}

// 显示借阅记录
function displayBorrowRecords(records) {
    const recordsContainer = document.getElementById('borrowRecordsContainer');
    
    if (!records || records.length === 0) {
        recordsContainer.innerHTML = '<p>暂无借阅记录</p>';
        return;
    }
    
    recordsContainer.innerHTML = records.map(record => {
        const statusClass = record.status === 0 ? 'status-not-returned' : 'status-returned';
        const statusText = record.status === 0 ? '未归还' : '已归还';
        const returnButton = record.status === 0 ? 
            `<button class="btn btn-secondary" onclick="returnBook(${record.id})">归还</button>` : '';
        
        return `
            <div class="borrow-record-item">
                <div class="borrow-record-info">
                    <h4>${record.bookTitle}</h4>
                    <p>借阅时间: ${record.borrowTime ? new Date(record.borrowTime).toLocaleString() : ''}</p>
                    <p>归还时间: ${record.returnTime ? new Date(record.returnTime).toLocaleString() : '未归还'}</p>
                    <p>状态: <span class="${statusClass}">${statusText}</span></p>
                </div>
                <div class="borrow-record-actions">
                    ${returnButton}
                </div>
            </div>
        `;
    }).join('');
}

// 显示借阅记录分页控件
function displayBorrowPagination(pageData, currentPage) {
    const paginationContainer = document.getElementById('borrowPagination');
    const totalPages = pageData.pages;
    
    if (totalPages <= 1) {
        paginationContainer.innerHTML = '';
        return;
    }
    
    let paginationHTML = '';
    
    // 上一页按钮
    if (currentPage > 1) {
        paginationHTML += `<button class="btn btn-secondary" onclick="loadBorrowRecords(${currentPage - 1})">上一页</button>`;
    }
    
    // 页码按钮
    for (let i = Math.max(1, currentPage - 2); i <= Math.min(totalPages, currentPage + 2); i++) {
        if (i === currentPage) {
            paginationHTML += `<button class="btn btn-primary" disabled>${i}</button>`;
        } else {
            paginationHTML += `<button class="btn btn-secondary" onclick="loadBorrowRecords(${i})">${i}</button>`;
        }
    }
    
    // 下一页按钮
    if (currentPage < totalPages) {
        paginationHTML += `<button class="btn btn-secondary" onclick="loadBorrowRecords(${currentPage + 1})">下一页</button>`;
    }
    
    paginationContainer.innerHTML = paginationHTML;
}

// 搜索借阅记录
function searchBorrowRecords() {
    // 简化实现，直接重新加载第一页
    loadBorrowRecords(1);
}

// 归还图书
function returnBook(recordId) {
    // 检查用户是否已登录
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    if (!currentUser) {
        alert('请先登录后再进行归还操作');
        window.location.href = 'login.html';
        return;
    }
    
    // 确认归还
    if (!confirm('确定要归还这本书吗？')) {
        return;
    }
    
    // 发送归还请求
    fetch(`/api/borrows/${recordId}/return`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            alert('归还成功！');
            // 重新加载借阅记录
            loadBorrowRecords();
            // 重新加载图书列表以更新库存
            if (document.getElementById('booksContainer')) {
                loadBooks();
            }
            // 如果在分类页面，也更新分类下的图书列表
            if (document.getElementById('categoryBooksContainer')) {
                // 需要获取当前分类ID，这里简化处理
                loadCategories();
            }
        } else {
            alert('归还失败：' + (data.message || '请稍后重试'));
        }
    })
    .catch(error => {
        console.error('归还请求失败:', error);
        alert('归还请求失败，请稍后重试');
    });
}

// 退出登录
function logout() {
    if (confirm('确定要退出登录吗？')) {
        // 清除本地存储的用户信息
        localStorage.removeItem('currentUser');
        // 跳转到登录页面
        window.location.href = 'login.html';
    }
}

// 管理员功能
function showSection(sectionId) {
    // 隐藏所有部分
    document.getElementById('bookManagement').style.display = 'none';
    document.getElementById('categoryManagement').style.display = 'none';
    document.getElementById('userManagement').style.display = 'none';
    
    // 显示选中的部分
    document.getElementById(sectionId).style.display = 'block';
}

// 加载管理员图书列表
function loadAdminBooks(page = 1, size = 12) {
    const booksContainer = document.getElementById('adminBooksContainer');
    const paginationContainer = document.getElementById('adminBooksPagination');
    
    // 显示加载状态
    booksContainer.innerHTML = '<p style="text-align: center; grid-column: 1 / -1;">加载中...</p>';
    
    // 发送请求获取图书列表
    fetch(`/api/books?page=${page}&size=${size}`)
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            displayAdminBooks(data.data.records);
            displayAdminPagination(data.data, page);
        } else {
            booksContainer.innerHTML = '<p style="text-align: center; grid-column: 1 / -1;">加载图书列表失败</p>';
        }
    })
    .catch(error => {
        console.error('加载图书列表失败:', error);
        booksContainer.innerHTML = '<p style="text-align: center; grid-column: 1 / -1;">加载图书列表失败，请稍后重试</p>';
    });
}

// 显示管理员图书列表
function displayAdminBooks(books) {
    const booksContainer = document.getElementById('adminBooksContainer');
    
    if (!books || books.length === 0) {
        booksContainer.innerHTML = '<p style="text-align: center; grid-column: 1 / -1;">暂无图书数据</p>';
        return;
    }
    
    booksContainer.innerHTML = books.map(book => `
        <div class="book-card">
            <div class="book-cover">
                <span>📚</span>
            </div>
            <div class="book-info">
                <h3>${book.title}</h3>
                <p>作者: ${book.author}</p>
                <p>ISBN: ${book.isbn}</p>
                <p>分类: ${book.categoryId || '未分类'}</p>
                <p>库存: ${book.stock}</p>
                <div class="book-actions">
                    <button class="btn btn-primary" onclick="showEditBookForm(${book.id})">编辑</button>
                    <button class="btn btn-secondary" onclick="deleteBook(${book.id})">删除</button>
                </div>
            </div>
        </div>
    `).join('');
}

// 显示管理员分页控件
function displayAdminPagination(pageData, currentPage) {
    const paginationContainer = document.getElementById('adminBooksPagination');
    const totalPages = pageData.pages;
    
    if (totalPages <= 1) {
        paginationContainer.innerHTML = '';
        return;
    }
    
    let paginationHTML = '';
    
    // 上一页按钮
    if (currentPage > 1) {
        paginationHTML += `<button class="btn btn-secondary" onclick="loadAdminBooks(${currentPage - 1})">上一页</button>`;
    }
    
    // 页码按钮
    for (let i = Math.max(1, currentPage - 2); i <= Math.min(totalPages, currentPage + 2); i++) {
        if (i === currentPage) {
            paginationHTML += `<button class="btn btn-primary" disabled>${i}</button>`;
        } else {
            paginationHTML += `<button class="btn btn-secondary" onclick="loadAdminBooks(${i})">${i}</button>`;
        }
    }
    
    // 下一页按钮
    if (currentPage < totalPages) {
        paginationHTML += `<button class="btn btn-secondary" onclick="loadAdminBooks(${currentPage + 1})">下一页</button>`;
    }
    
    paginationContainer.innerHTML = paginationHTML;
}

// 显示添加图书表单
function showAddBookForm() {
    // 加载分类选项
    loadCategoryOptions('addBookCategoryId');
    
    // 显示模态框
    document.getElementById('addBookModal').style.display = 'block';
}

// 关闭添加图书模态框
function closeAddBookModal() {
    document.getElementById('addBookModal').style.display = 'none';
    // 清空表单
    document.getElementById('addBookForm').reset();
}

// 添加图书
function addBook() {
    const title = document.getElementById('addBookTitle').value.trim();
    const author = document.getElementById('addBookAuthor').value.trim();
    const isbn = document.getElementById('addBookIsbn').value.trim();
    const categoryId = document.getElementById('addBookCategoryId').value;
    const stock = document.getElementById('addBookStock').value;
    const description = document.getElementById('addBookDescription').value.trim();
    
    // 简单验证
    if (!title || !author || !isbn || !categoryId || stock === '') {
        alert('请填写所有必填字段');
        return;
    }
    
    // 显示加载状态
    const submitButton = document.querySelector('#addBookForm .btn');
    const originalText = submitButton.textContent;
    submitButton.textContent = '添加中...';
    submitButton.disabled = true;
    
    // 发送添加请求
    fetch('/api/admin/books', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            title: title,
            author: author,
            isbn: isbn,
            categoryId: parseInt(categoryId),
            stock: parseInt(stock),
            description: description
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            alert('图书添加成功！');
            // 关闭模态框
            closeAddBookModal();
            // 重新加载图书列表
            loadAdminBooks();
        } else {
            alert('添加失败：' + (data.message || '请稍后重试'));
        }
    })
    .catch(error => {
        console.error('添加图书请求失败:', error);
        alert('添加图书请求失败，请稍后重试');
    })
    .finally(() => {
        // 恢复按钮状态
        submitButton.textContent = originalText;
        submitButton.disabled = false;
    });
}

// 显示编辑图书表单
function showEditBookForm(bookId) {
    // 发送请求获取图书详细信息
    fetch(`/api/books/${bookId}`)
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            const book = data.data;
            // 填充表单数据
            document.getElementById('editBookId').value = book.id;
            document.getElementById('editBookTitle').value = book.title;
            document.getElementById('editBookAuthor').value = book.author;
            document.getElementById('editBookIsbn').value = book.isbn;
            document.getElementById('editBookStock').value = book.stock;
            document.getElementById('editBookDescription').value = book.description || '';
            
            // 加载分类选项并选中当前分类
            loadCategoryOptions('editBookCategoryId', book.categoryId);
            
            // 显示模态框
            document.getElementById('editBookModal').style.display = 'block';
        } else {
            alert('获取图书信息失败：' + (data.message || '请稍后重试'));
        }
    })
    .catch(error => {
        console.error('获取图书信息失败:', error);
        alert('获取图书信息失败，请稍后重试');
    });
}

// 关闭编辑图书模态框
function closeEditBookModal() {
    document.getElementById('editBookModal').style.display = 'none';
}

// 更新图书
function updateBook() {
    const bookId = document.getElementById('editBookId').value;
    const title = document.getElementById('editBookTitle').value.trim();
    const author = document.getElementById('editBookAuthor').value.trim();
    const isbn = document.getElementById('editBookIsbn').value.trim();
    const categoryId = document.getElementById('editBookCategoryId').value;
    const stock = document.getElementById('editBookStock').value;
    const description = document.getElementById('editBookDescription').value.trim();
    
    // 简单验证
    if (!title || !author || !isbn || !categoryId || stock === '') {
        alert('请填写所有必填字段');
        return;
    }
    
    // 显示加载状态
    const submitButton = document.querySelector('#editBookForm .btn');
    const originalText = submitButton.textContent;
    submitButton.textContent = '保存中...';
    submitButton.disabled = true;
    
    // 发送更新请求
    fetch(`/api/admin/books/${bookId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            title: title,
            author: author,
            isbn: isbn,
            categoryId: parseInt(categoryId),
            stock: parseInt(stock),
            description: description
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            alert('图书更新成功！');
            // 关闭模态框
            closeEditBookModal();
            // 重新加载图书列表
            loadAdminBooks();
        } else {
            alert('更新失败：' + (data.message || '请稍后重试'));
        }
    })
    .catch(error => {
        console.error('更新图书请求失败:', error);
        alert('更新图书请求失败，请稍后重试');
    })
    .finally(() => {
        // 恢复按钮状态
        submitButton.textContent = originalText;
        submitButton.disabled = false;
    });
}

// 删除图书
function deleteBook(bookId) {
    if (!confirm('确定要删除这本书吗？')) {
        return;
    }
    
    // 发送删除请求
    fetch(`/api/admin/books/${bookId}`, {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            alert('删除成功！');
            // 重新加载图书列表
            loadAdminBooks();
        } else {
            alert('删除失败：' + (data.message || '请稍后重试'));
        }
    })
    .catch(error => {
        console.error('删除请求失败:', error);
        alert('删除请求失败，请稍后重试');
    });
}

// 显示更新库存表单
function showUpdateStockForm(bookId, currentStock) {
    const newStock = prompt('请输入新的库存数量:', currentStock);
    if (newStock !== null && newStock !== '' && !isNaN(newStock) && newStock >= 0) {
        // 发送更新库存请求
        fetch(`/api/admin/books/${bookId}/stock?stock=${newStock}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                alert('库存更新成功！');
                // 重新加载图书列表
                loadAdminBooks();
            } else {
                alert('库存更新失败：' + (data.message || '请稍后重试'));
            }
        })
        .catch(error => {
            console.error('更新库存请求失败:', error);
            alert('更新库存请求失败，请稍后重试');
        });
    }
}

// 加载管理员分类列表
function loadAdminCategories() {
    const categoriesContainer = document.getElementById('adminCategoriesContainer');
    
    // 显示加载状态
    categoriesContainer.innerHTML = '<p style="text-align: center; grid-column: 1 / -1;">加载中...</p>';
    
    // 发送请求获取分类列表
    fetch('/api/admin/categories')
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            displayAdminCategories(data.data);
        } else {
            categoriesContainer.innerHTML = '<p style="text-align: center; grid-column: 1 / -1;">加载分类列表失败</p>';
        }
    })
    .catch(error => {
        console.error('加载分类列表失败:', error);
        categoriesContainer.innerHTML = '<p style="text-align: center; grid-column: 1 / -1;">加载分类列表失败，请稍后重试</p>';
    });
}

// 显示管理员分类列表
function displayAdminCategories(categories) {
    const categoriesContainer = document.getElementById('adminCategoriesContainer');
    
    if (!categories || categories.length === 0) {
        categoriesContainer.innerHTML = '<p style="text-align: center; grid-column: 1 / -1;">暂无分类数据</p>';
        return;
    }
    
    categoriesContainer.innerHTML = categories.map(category => `
        <div class="category-card">
            <div class="category-header">
                <span>📚</span>
            </div>
            <div class="category-info">
                <h3>${category.name}</h3>
                <p>${category.description || '暂无描述'}</p>
                <div class="book-actions">
                    <button class="btn btn-primary" onclick="showEditCategoryForm(${category.id})">编辑</button>
                    <button class="btn btn-secondary" onclick="deleteCategory(${category.id})">删除</button>
                </div>
            </div>
        </div>
    `).join('');
}

// 显示添加分类表单
function showAddCategoryForm() {
    // 显示模态框
    document.getElementById('addCategoryModal').style.display = 'block';
}

// 关闭添加分类模态框
function closeAddCategoryModal() {
    document.getElementById('addCategoryModal').style.display = 'none';
    // 清空表单
    document.getElementById('addCategoryForm').reset();
}

// 添加分类
function addCategory() {
    const name = document.getElementById('addCategoryName').value.trim();
    const description = document.getElementById('addCategoryDescription').value.trim();
    
    // 简单验证
    if (!name) {
        alert('请填写分类名称');
        return;
    }
    
    // 显示加载状态
    const submitButton = document.querySelector('#addCategoryForm .btn');
    const originalText = submitButton.textContent;
    submitButton.textContent = '添加中...';
    submitButton.disabled = true;
    
    // 发送添加请求
    fetch('/api/admin/categories', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            name: name,
            description: description
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            alert('分类添加成功！');
            // 关闭模态框
            closeAddCategoryModal();
            // 重新加载分类列表
            loadAdminCategories();
        } else {
            alert('添加失败：' + (data.message || '请稍后重试'));
        }
    })
    .catch(error => {
        console.error('添加分类请求失败:', error);
        alert('添加分类请求失败，请稍后重试');
    })
    .finally(() => {
        // 恢复按钮状态
        submitButton.textContent = originalText;
        submitButton.disabled = false;
    });
}

// 显示编辑分类表单
function showEditCategoryForm(categoryId) {
    // 发送请求获取分类详细信息
    fetch(`/api/categories/${categoryId}`)
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            const category = data.data;
            // 填充表单数据
            document.getElementById('editCategoryId').value = category.id;
            document.getElementById('editCategoryName').value = category.name;
            document.getElementById('editCategoryDescription').value = category.description || '';
            
            // 显示模态框
            document.getElementById('editCategoryModal').style.display = 'block';
        } else {
            alert('获取分类信息失败：' + (data.message || '请稍后重试'));
        }
    })
    .catch(error => {
        console.error('获取分类信息失败:', error);
        alert('获取分类信息失败，请稍后重试');
    });
}

// 关闭编辑分类模态框
function closeEditCategoryModal() {
    document.getElementById('editCategoryModal').style.display = 'none';
}

// 更新分类
function updateCategory() {
    const categoryId = document.getElementById('editCategoryId').value;
    const name = document.getElementById('editCategoryName').value.trim();
    const description = document.getElementById('editCategoryDescription').value.trim();
    
    // 简单验证
    if (!name) {
        alert('请填写分类名称');
        return;
    }
    
    // 显示加载状态
    const submitButton = document.querySelector('#editCategoryForm .btn');
    const originalText = submitButton.textContent;
    submitButton.textContent = '保存中...';
    submitButton.disabled = true;
    
    // 发送更新请求
    fetch(`/api/admin/categories/${categoryId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            name: name,
            description: description
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            alert('分类更新成功！');
            // 关闭模态框
            closeEditCategoryModal();
            // 重新加载分类列表
            loadAdminCategories();
        } else {
            alert('更新失败：' + (data.message || '请稍后重试'));
        }
    })
    .catch(error => {
        console.error('更新分类请求失败:', error);
        alert('更新分类请求失败，请稍后重试');
    })
    .finally(() => {
        // 恢复按钮状态
        submitButton.textContent = originalText;
        submitButton.disabled = false;
    });
}

// 删除分类
function deleteCategory(categoryId) {
    if (!confirm('确定要删除这个分类吗？')) {
        return;
    }
    
    // 发送删除请求
    fetch(`/api/admin/categories/${categoryId}`, {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            alert('删除成功！');
            // 重新加载分类列表
            loadAdminCategories();
        } else {
            alert('删除失败：' + (data.message || '请稍后重试'));
        }
    })
    .catch(error => {
        console.error('删除请求失败:', error);
        alert('删除请求失败，请稍后重试');
    });
}

// 加载管理员用户列表
function loadAdminUsers() {
    const usersContainer = document.getElementById('adminUsersContainer');
    
    // 显示加载状态
    usersContainer.innerHTML = '<p>加载中...</p>';
    
    // 发送请求获取用户列表
    fetch('/api/admin/users')
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            displayAdminUsers(data.data);
        } else {
            usersContainer.innerHTML = '<p>加载用户列表失败</p>';
        }
    })
    .catch(error => {
        console.error('加载用户列表失败:', error);
        usersContainer.innerHTML = '<p>加载用户列表失败，请稍后重试</p>';
    });
}

// 显示管理员用户列表
function displayAdminUsers(users) {
    const usersContainer = document.getElementById('adminUsersContainer');
    
    if (!users || users.length === 0) {
        usersContainer.innerHTML = '<p>暂无用户数据</p>';
        return;
    }
    
    usersContainer.innerHTML = users.map(user => {
        const roleClass = user.role === 'ADMIN' ? 'role-admin' : 'role-user';
        const roleText = user.role === 'ADMIN' ? '管理员' : '普通用户';
        
        return `
            <div class="user-card">
                <h4>${user.username}</h4>
                <p>真实姓名: ${user.realName}</p>
                <p>联系电话: ${user.phone}</p>
                <p>角色: <span class="${roleClass}">${roleText}</span></p>
                <div class="user-actions">
                    <button class="btn btn-primary" onclick="changeUserRole(${user.id}, '${user.role}')">更改角色</button>
                </div>
            </div>
        `;
    }).join('');
}

// 更改用户角色
function changeUserRole(userId, currentRole) {
    const newRole = currentRole === 'ADMIN' ? 'USER' : 'ADMIN';
    const roleText = newRole === 'ADMIN' ? '管理员' : '普通用户';
    
    if (!confirm(`确定要将该用户的角色更改为${roleText}吗？`)) {
        return;
    }
    
    // 发送更新角色请求
    fetch(`/api/admin/users/${userId}/role?role=${newRole}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            alert('角色更新成功！');
            // 重新加载用户列表
            loadAdminUsers();
        } else {
            alert('角色更新失败：' + (data.message || '请稍后重试'));
        }
    })
    .catch(error => {
        console.error('更新角色请求失败:', error);
        alert('更新角色请求失败，请稍后重试');
    });
}

// 加载分类选项
function loadCategoryOptions(selectId, selectedCategoryId = null) {
    const selectElement = document.getElementById(selectId);
    
    // 显示加载状态
    selectElement.innerHTML = '<option value="">加载中...</option>';
    
    // 发送请求获取分类列表
    fetch('/api/admin/categories')
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            const categories = data.data;
            if (categories && categories.length > 0) {
                // 清空选项
                selectElement.innerHTML = '';
                
                // 添加选项
                categories.forEach(category => {
                    const option = document.createElement('option');
                    option.value = category.id;
                    option.textContent = category.name;
                    if (selectedCategoryId && category.id == selectedCategoryId) {
                        option.selected = true;
                    }
                    selectElement.appendChild(option);
                });
            } else {
                selectElement.innerHTML = '<option value="">暂无分类</option>';
            }
        } else {
            selectElement.innerHTML = '<option value="">加载失败</option>';
        }
    })
    .catch(error => {
        console.error('加载分类列表失败:', error);
        selectElement.innerHTML = '<option value="">加载失败</option>';
    });
}

// 通用API调用函数
function apiCall(url, options = {}) {
    const defaultOptions = {
        headers: {
            'Content-Type': 'application/json'
        }
    };
    
    return fetch(url, { ...defaultOptions, ...options })
        .then(response => response.json())
        .catch(error => {
            console.error('API调用失败:', error);
            throw error;
        });
}

// 通用确认对话框函数
function confirmAction(message) {
    return confirm(message);
}

// 通用提示函数
function showMessage(message, isError = false) {
    if (isError) {
        console.error(message);
    } else {
        console.log(message);
    }
    alert(message);
}

// 通用加载状态管理函数
function setLoadingState(button, loadingText = '处理中...', disabled = true) {
    const originalText = button.textContent;
    if (disabled) {
        button.textContent = loadingText;
        button.disabled = true;
    } else {
        button.textContent = originalText;
        button.disabled = false;
    }
    return originalText;
}

// 通用表单验证函数
function validateForm(fields) {
    let isValid = true;
    const errors = {};
    
    fields.forEach(field => {
        const element = document.getElementById(field.id);
        const value = element.value.trim();
        
        // 重置错误状态
        element.classList.remove('error');
        if (field.errorElement) {
            document.getElementById(field.errorElement).textContent = '';
        }
        
        // 执行验证
        if (field.required && !value) {
            errors[field.id] = field.errorMessage || '此字段为必填项';
            element.classList.add('error');
            if (field.errorElement) {
                document.getElementById(field.errorElement).textContent = errors[field.id];
            }
            isValid = false;
        } else if (field.pattern && value && !field.pattern.test(value)) {
            errors[field.id] = field.patternMessage || '格式不正确';
            element.classList.add('error');
            if (field.errorElement) {
                document.getElementById(field.errorElement).textContent = errors[field.id];
            }
            isValid = false;
        } else if (field.minLength && value.length < field.minLength) {
            errors[field.id] = `长度不能少于${field.minLength}位`;
            element.classList.add('error');
            if (field.errorElement) {
                document.getElementById(field.errorElement).textContent = errors[field.id];
            }
            isValid = false;
        }
    });
    
    return { isValid, errors };
}

// 通用模态框操作函数
function showModal(modalId) {
    document.getElementById(modalId).style.display = 'block';
}

function hideModal(modalId) {
    document.getElementById(modalId).style.display = 'none';
}

// 通用数据加载函数
function loadData(url, successCallback, errorCallback) {
    apiCall(url)
        .then(data => {
            if (data.code === 200) {
                successCallback(data.data);
            } else {
                if (errorCallback) {
                    errorCallback(data.message || '加载失败');
                } else {
                    showMessage('加载失败：' + (data.message || '请稍后重试'), true);
                }
            }
        })
        .catch(error => {
            const errorMessage = '加载数据失败，请稍后重试';
            if (errorCallback) {
                errorCallback(errorMessage);
            } else {
                showMessage(errorMessage, true);
            }
        });
}

// 通用数据提交函数
function submitData(url, method, data, successCallback, errorCallback) {
    apiCall(url, {
        method: method,
        body: JSON.stringify(data)
    })
    .then(response => {
        if (response.code === 200) {
            if (successCallback) {
                successCallback(response.message || '操作成功');
            } else {
                showMessage('操作成功！');
            }
        } else {
            if (errorCallback) {
                errorCallback(response.message || '操作失败');
            } else {
                showMessage('操作失败：' + (response.message || '请稍后重试'), true);
            }
        }
    })
    .catch(error => {
        const errorMessage = '提交数据失败，请稍后重试';
        if (errorCallback) {
            errorCallback(errorMessage);
        } else {
            showMessage(errorMessage, true);
        }
    });
}

// 页面切换功能（已在HTML中通过href实现）
// 如果需要更复杂的页面切换逻辑，可以在这里添加

// 其他交互功能可以在这里添加

// 添加一些主页的交互效果
function initHomePage() {
    // 为主页的特色卡片添加悬停效果
    const featureCards = document.querySelectorAll('.feature-card');
    featureCards.forEach(card => {
        card.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-10px)';
        });
        
        card.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0)';
        });
    });
    
    // 为按钮添加点击效果
    const buttons = document.querySelectorAll('.btn');
    buttons.forEach(button => {
        button.addEventListener('mousedown', function() {
            this.style.transform = 'scale(0.98)';
        });
        
        button.addEventListener('mouseup', function() {
            this.style.transform = 'scale(1)';
        });
        
        button.addEventListener('mouseleave', function() {
            this.style.transform = 'scale(1)';
        });
    });
}

// 页面切换时的平滑过渡效果
function smoothPageTransition() {
    // 添加页面加载动画
    document.body.classList.add('page-loading');
    
    window.addEventListener('load', function() {
        document.body.classList.remove('page-loading');
        document.body.classList.add('page-loaded');
    });
}

// 初始化页面功能
function initPage() {
    // 根据当前页面初始化相应功能
    if (document.getElementById('loginForm')) {
        // 登录页面
        console.log('初始化登录页面');
    } else if (document.getElementById('registerForm')) {
        // 注册页面
        console.log('初始化注册页面');
    } else if (document.getElementById('booksContainer')) {
        // 图书列表页面
        console.log('初始化图书列表页面');
        loadBooks(1);
    } else if (document.getElementById('categoriesContainer')) {
        // 图书分类页面
        console.log('初始化图书分类页面');
        loadCategories();
    } else if (document.getElementById('profileForm')) {
        // 个人中心页面
        console.log('初始化个人中心页面');
        loadUserProfile();
        loadBorrowRecords(1);
    } else if (document.getElementById('adminBooksContainer')) {
        // 管理员页面
        console.log('初始化管理员页面');
        // 检查用户是否为管理员
        checkAdminPermission().then(isAdmin => {
            if (isAdmin) {
                // 初始化管理员页面
                loadAdminBooks(1);
                loadAdminCategories();
                loadAdminUsers();
            } else {
                // 不是管理员，显示权限不足提示
                document.querySelector('.admin-section').innerHTML = '<p style="text-align: center; color: #e74c3c;">权限不足，只有管理员才能访问此页面</p>';
            }
        });
    } else {
        // 主页
        initHomePage();
        console.log('初始化主页');
    }
    
    // 页面过渡效果
    smoothPageTransition();
    
    // 根据用户角色更新导航栏
    updateNavbarByRole();
}

// 根据用户角色更新导航栏
function updateNavbarByRole() {
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    const navMenus = document.querySelectorAll('.nav-menu');
    
    if (!currentUser) {
        // 未登录用户，显示基础导航栏
        navMenus.forEach(navMenu => {
            navMenu.innerHTML = `
                <li><a href="index.html" class="nav-link ${isCurrentPage('index.html') ? 'active' : ''}">首页</a></li>
                <li><a href="books.html" class="nav-link ${isCurrentPage('books.html') ? 'active' : ''}">图书浏览</a></li>
                <li><a href="categories.html" class="nav-link ${isCurrentPage('categories.html') ? 'active' : ''}">图书分类</a></li>
                <li><a href="login.html" class="nav-link ${isCurrentPage('login.html') ? 'active' : ''}">登录</a></li>
            `;
        });
        return;
    }
    
    // 已登录用户，根据角色显示不同菜单
    navMenus.forEach(navMenu => {
        if (currentUser.role === 'ADMIN') {
            // 管理员用户
            navMenu.innerHTML = `
                <li><a href="index.html" class="nav-link ${isCurrentPage('index.html') ? 'active' : ''}">首页</a></li>
                <li><a href="books.html" class="nav-link ${isCurrentPage('books.html') ? 'active' : ''}">图书浏览</a></li>
                <li><a href="categories.html" class="nav-link ${isCurrentPage('categories.html') ? 'active' : ''}">图书分类</a></li>
                <li><a href="profile.html" class="nav-link ${isCurrentPage('profile.html') ? 'active' : ''}">个人中心</a></li>
                <li><a href="admin.html" class="nav-link ${isCurrentPage('admin.html') ? 'active' : ''}">管理员中心</a></li>
                <li><a href="login.html" class="nav-link" id="logoutLink">退出</a></li>
            `;
        } else {
            // 普通用户
            navMenu.innerHTML = `
                <li><a href="index.html" class="nav-link ${isCurrentPage('index.html') ? 'active' : ''}">首页</a></li>
                <li><a href="books.html" class="nav-link ${isCurrentPage('books.html') ? 'active' : ''}">图书浏览</a></li>
                <li><a href="categories.html" class="nav-link ${isCurrentPage('categories.html') ? 'active' : ''}">图书分类</a></li>
                <li><a href="profile.html" class="nav-link ${isCurrentPage('profile.html') ? 'active' : ''}">个人中心</a></li>
                <li><a href="login.html" class="nav-link" id="logoutLink">退出</a></li>
            `;
        }
    });
    
    // 重新绑定退出登录事件
    const logoutLink = document.getElementById('logoutLink');
    if (logoutLink) {
        logoutLink.addEventListener('click', function(e) {
            e.preventDefault();
            logout();
        });
    }
}

// 判断当前页面
function isCurrentPage(pageName) {
    return window.location.pathname.includes(pageName);
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', initPage);